<template>
  <div class="pdf-viewer">
    <div class="toolbar">
      <el-button @click="prevPage" :disabled="currentPage <= 1">上一页</el-button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <el-button @click="nextPage" :disabled="currentPage >= totalPages">下一页</el-button>
      <el-select v-model="scale" style="width: 120px">
        <el-option label="50%" value="0.5" />
        <el-option label="100%" value="1" />
        <el-option label="150%" value="1.5" />
        <el-option label="200%" value="2" />
      </el-select>
    </div>
    <div class="pdf-container" ref="container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import * as pdfjsLib from 'pdfjs-dist'
import { ElMessage } from 'element-plus'

// 配置PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js'

const route = useRoute()
const container = ref<HTMLElement>()
const currentPage = ref(1)
const totalPages = ref(0)
const scale = ref('1')
let pdfDoc: any = null

// 加载PDF文档
const loadPdf = async () => {
  try {
    const id = route.params.id
    const loadingTask = pdfjsLib.getDocument({
      url: '/api/pdf/view',
      method: 'POST',
      body: JSON.stringify({ id }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
    pdfDoc = await loadingTask.promise
    totalPages.value = pdfDoc.numPages
    renderPage(currentPage.value)
  } catch (error) {
    ElMessage.error('PDF加载失败')
  }
}

// 渲染页面
const renderPage = async (num: number) => {
  if (!pdfDoc) return
  
  try {
    const page = await pdfDoc.getPage(num)
    const viewport = page.getViewport({ scale: parseFloat(scale.value) })
    
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.height = viewport.height
    canvas.width = viewport.width
    
    if (container.value) {
      container.value.innerHTML = ''
      container.value.appendChild(canvas)
    }
    
    await page.render({
      canvasContext: context,
      viewport: viewport
    }).promise
  } catch (error) {
    ElMessage.error('页面渲染失败')
  }
}

// 翻页功能
const prevPage = () => {
  if (currentPage.value <= 1) return
  currentPage.value--
  renderPage(currentPage.value)
}

const nextPage = () => {
  if (currentPage.value >= totalPages.value) return
  currentPage.value++
  renderPage(currentPage.value)
}

// 监听缩放变化
watch(scale, () => {
  renderPage(currentPage.value)
})

onMounted(() => {
  loadPdf()
})
</script>

<style scoped>
.pdf-viewer {
  width: 100%;
  padding: 20px;
  background: #f5f5f5;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.pdf-container {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
</style> 